import Taro from "@tarojs/taro";
import { Http, CodeError, HttpBuilder} from "foundation";

export class WXHttp implements Http {
  async send(): Promise<[string, CodeError]> {
    let headers:Record<string, string> = {};
    this.builder.headers().forEach(((value, key) => {
      headers[key] = value;
    }));

    let url = this.builder.baseUrl() + this.builder.uri();
    if (this.builder.uri().search(/^(http|https):\/\//)>=0) {
      url = this.builder.uri();
    }

    const ret = await Taro.request<string>({
      url:url,
      method:"GET",
      data:this.builder.content(),
      dataType:"json",
      responseType:"text",
    });


    return [ret.data, new CodeError(ret.errMsg, ret.statusCode)];
  }

  constructor(private builder: HttpBuilder) { }
}
